/*
 * 版权所有 (c) 华为技术有限公司 2022-2022
 */
package com.huawei.cameratest.Multi_instance;

import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraManager;
import android.os.Environment;
import android.os.StatFs;
import android.util.Log;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;


public class Utils {
    public static final SimpleDateFormat FORMAT_DATA =
            new SimpleDateFormat("yyyy-MM-dd_HHmmss", Locale.getDefault());
    public static final int SIZE_K = 1024;
    public static final int SIZE_M = 1024 * SIZE_K;
    public static String STORAGE_PATH = Environment.getExternalStorageDirectory().getPath();
    public static String PARENT_PATH = STORAGE_PATH + "/Video";

    public static String MIME_TYPE_264 = "video/avc";
    public static String MIME_TYPE_265 = "video/hevc";

    public static boolean checkValidCameraId( CameraManager mCameraManager, String mCameraId) {
        boolean res = false;
        String[] cameraIds = null;
        try {
            cameraIds = mCameraManager.getCameraIdList();
        } catch (CameraAccessException e) {
            e.printStackTrace();
            return res;
        }

        if (cameraIds.length == 0) {
            return res;
        }

        for (String cameraId : cameraIds) {
            if (mCameraId.equals(cameraId)) {
                res = true;
            }
        }
        return res;
    }

    public static long getTotalSize() {
        File file = Environment.getExternalStorageDirectory();
        StatFs statFs = new StatFs(file.getPath());
        long availableBlockCount = statFs.getAvailableBlocksLong();
        long blockSize = statFs.getBlockSizeLong();
        return availableBlockCount * blockSize;
    }

    public static byte[] toByteArray(int byteLength, int value) {
        return ByteBuffer.allocate(byteLength).order(ByteOrder.BIG_ENDIAN).putInt(value).array();
    }

    public static byte[] toByteArray(int byteLength, char value) {
        return ByteBuffer.allocate(byteLength).order(ByteOrder.BIG_ENDIAN).putChar(value).array();
    }

    public static byte[] toByteArray(int byteLength, short value) {
        return ByteBuffer.allocate(byteLength).order(ByteOrder.BIG_ENDIAN).putShort(value).array();
    }

    public static byte[] toByteArray(int byteLength, long value) {
        return ByteBuffer.allocate(byteLength).order(ByteOrder.BIG_ENDIAN).putLong(value).array();
    }

    public static byte[] toByteArray(int byteLength, byte[] value) {
        return ByteBuffer.allocate(byteLength).order(ByteOrder.BIG_ENDIAN).put(value).array();
    }

    public static byte[] getBytesFromChar(char[] chars) {
        Charset cs = Charset.forName("UTF-8");
        CharBuffer cb = CharBuffer.allocate(chars.length);
        cb.put(chars);
        cb.flip();
        ByteBuffer bb = cs.encode(cb);

        return bb.array();
    }

    public static String bytes2hex(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        String tmp = null;
        for (byte aByte: bytes) {
            // 将每个字节与0xFF进行与运算，然后转化为10进制，然后借助于Integer再转化为16进制
            tmp = Integer.toHexString(0xFF & aByte);
            if (tmp.length() == 1) {
                tmp = "0" + tmp;
            }
            sb.append(tmp);
        }
        return sb.toString();
    }

    public static String bytes2Binary(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        String tmp = null;
        for (byte aByte : bytes) {
            // 将每个字节与0xFF进行与运算，然后转化为10进制，然后借助于Integer再转化为2进制
            tmp = Integer.toBinaryString(aByte);
            sb.append(tmp);
        }
        return sb.toString();
    }

    public static String bytes2hex(byte bytes) {
        StringBuilder sb = new StringBuilder();
        String tmp = null;

        // 将每个字节与0xFF进行与运算，然后转化为10进制，然后借助于Integer再转化为16进制
        tmp = Integer.toHexString(0xFF & bytes);
        if (tmp.length() == 1) {
            tmp = "0" + tmp;
        }
        sb.append(tmp);

        return sb.toString();
    }

    public static byte[] toByteArray(int byteLength, String value) {
        try {
            ByteBuffer buffer = ByteBuffer.wrap("Content of the String".getBytes("utf-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }

    // https://blog.csdn.net/defonds/article/details/8782785
    public static int byteArrayToInt(byte[] bytes) {
        return (bytes[3] & 0xFF)
                | (bytes[2] & 0xFF) << 8
                | (bytes[1] & 0xFF) << 16
                | (bytes[0] & 0xFF) << 24;
    }

    // 合并多个byte数组
    public static byte[] mergerAllByte(byte[]... values) {
        int lengthByte = 0;
        for (int i = 0; i < values.length; i++) {
            lengthByte += values[i].length;
        }
        byte[] allByte = new byte[lengthByte];
        int countLength = 0;
        for (int i = 0; i < values.length; i++) {
            byte[] bytes = values[i];
            System.arraycopy(bytes, 0, allByte, countLength, bytes.length);
            countLength += bytes.length;
        }
        return allByte;
    }

    public static void writeToFile(FileOutputStream fileOutputStream, byte[] bytes, File file) {
        try {
            long fileStartFile = System.currentTimeMillis();
            fileOutputStream = new FileOutputStream(file);
            fileOutputStream.write(bytes);
            fileOutputStream.flush();
            long fileEndFile = System.currentTimeMillis();
            Log.i("Utils", "onImageAvailable: file time " + (fileEndFile - fileStartFile));
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fileOutputStream != null) {
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static File createFile() {
        String dir = Environment.getExternalStorageDirectory() + File.separator +
                "CameraResources" + File.separator;
        File dirFile = new File(dir);
        if (!dirFile.exists()) {
            if (!dirFile.mkdir()) {
                return null;
            }
        }
        long time = System.currentTimeMillis();
        Date date = new Date(time);
        SimpleDateFormat format = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss");
        String savePicName = format.format(date) + "_picture" + ".jpg";
        File file = new File(dir + savePicName);
        return file;
    }

    public static String checkMediaType(String str, String type) {
        if (type.equals("H264")) {
            return MIME_TYPE_264;
        } else {
            return MIME_TYPE_265;
        }
    }


}